/*
 * @Author: xiaosihan 
 * @Date: 2023-08-11 01:17:36 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-11-19 19:26:04
 */

import { fabric } from "fabric";
import JsBarcode from "jsbarcode";

// 条码
export default class FabricBarCode extends fabric.Object {
  constructor() {
    super();
  }

  //条码
  type = "barCode";

  declare id: string;

  declare value: string;

  centeredRotation = true;

  originX = "center";

  originY = "center";

  // 缩小时不翻转
  lockScalingFlip = true;

  width = 300;

  height = 100;

  scaleX = 1;

  scaleY = 1;

  img = new Image();

  async setValue(value: string = "10000000", text: string = "") {
    this.value = value;

    // 创建一个临时的 SVG 元素
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

    // 使用 JsBarcode 生成 SVG 图像
    JsBarcode(svg, this.value, {
      format: "CODE128", // 条码格式，这里使用 CODE128
      width: 6,
      fontSize: 50,
      displayValue: true, // 是否显示条码值
      text: `${value}${text}`
    });

    // 将 SVG 图像转换为 XML 字符串
    var svgString = new XMLSerializer().serializeToString(svg);

    await new Promise<void>((resolve, reject) => {
      // 当图像加载完成后，在 Canvas 上下文中绘制图像
      this.img.onload = () => {
        resolve();
      };
      var blob = new Blob([svgString], { type: "image/svg+xml" });
      var url = URL.createObjectURL(blob);
      this.img.src = url;
    });

  }

  // 初始化对象
  static fromObject(prames: any, callback: (obj: FabricBarCode) => {}) {
    const fabricBarCode = new FabricBarCode();
    fabricBarCode.setValue(prames.value).then(() => {
      fabricBarCode.set(prames);
      callback(fabricBarCode);
    });
  }

  // 绘制元素
  drawObject(ctx: CanvasRenderingContext2D): void {
    const { naturalWidth, naturalHeight } = this.img;
    const { width, height } = this;
    const scale = Math.min(width / naturalWidth, height / naturalHeight);
    const drawWidth = naturalWidth * scale;
    const drawHeight = naturalHeight * scale;
    ctx.save();
    ctx.drawImage(this.img,
      drawWidth / -2, drawHeight / -2,
      drawWidth, drawHeight,
    );
    ctx.strokeRect(width / -2, height / -2, width, height);
    ctx.restore();
  }

  toObject(propertiesToInclude: Array<string> = []) {
    return super.toObject(propertiesToInclude.concat(["id", "value"]));
  }

}


//@ts-ignore
fabric.BarCode = FabricBarCode;